package com.stxx.framwork.exception;


import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import cn.dev33.satoken.exception.NotRoleException;
import cn.hutool.http.HttpStatus;

import com.stxx.framwork.domain.R;
import lombok.extern.slf4j.Slf4j;
import org.noear.solon.annotation.Component;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.Filter;
import org.noear.solon.core.handle.FilterChain;
import org.yaml.snakeyaml.constructor.DuplicateKeyException;

/**
 * @author noear 2022/10/4 created
 */
@Slf4j
@Component
public class GlobalErrorFilter implements Filter {
    @Override
    public void doFilter(Context ctx, FilterChain chain) throws Throwable {
        try {
            chain.doFilter(ctx);
        }
        catch (NotPermissionException e) {
            e.printStackTrace();
            //log.error("请求地址'{}',权限码校验失败'{}'",ctx.uri(),e.getMessage());
            ctx.render(R.fail(HttpStatus.HTTP_FORBIDDEN, "没有访问权限，请联系管理员授权"));
        }catch (NotRoleException e) {
            e.printStackTrace();
            //log.error("请求地址'{}',权限码校验失败'{}'",ctx.uri(),e.getMessage());
            ctx.render(R.fail(HttpStatus.HTTP_FORBIDDEN, "没有访问权限，请联系管理员授权"));
        }catch (NotLoginException e) {
            e.printStackTrace();
            //log.error("请求地址'{}',认证失败'{}',无法访问系统资源",ctx.uri(),e.getMessage());
            ctx.render(R.fail(HttpStatus.HTTP_UNAUTHORIZED, "认证失败，无法访问系统资源"));
        } catch (DuplicateKeyException e) {
            e.printStackTrace();
            //log.error("请求地址'{}',数据库中已存在记录'{}'",ctx.uri(),e.getMessage());
            ctx.render(R.fail(601, "数据库中已存在该记录，请联系管理员确认"));
        }catch (ServiceException e) {
            e.printStackTrace();
            //log.error("请求地址'{}',权限码校验失败'{}'",ctx.uri(),e.getMessage());
            ctx.render(R.fail(e.getCode(), e.getMessage()));
        }catch (RuntimeException e) {
            e.printStackTrace();
            //log.error("请求地址'{}',发生未知异常'{}'",ctx.uri(),e.getMessage());
            ctx.render(R.fail(e.getMessage()));
        }catch (Exception e) {
            e.printStackTrace();
            //log.error("请求地址'{}',发生系统异常'{}'",ctx.uri(),e.getMessage());
            ctx.render(R.fail(HttpStatus.HTTP_FORBIDDEN, "没有访问权限，请联系管理员授权"));
        }
    }
}